package retry;

import boot.RpcApplication;
import com.github.rholder.retry.*;
import lombok.extern.slf4j.Slf4j;
import model.RpcResponse;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * 固定时间间隔重试
 */
@Slf4j
public class FixedTimeIntervalStrategy implements RetryStrategy{
    public RpcResponse retry(Callable<RpcResponse> callable) throws Exception{
        Retryer<RpcResponse> retryer = RetryerBuilder.<RpcResponse>newBuilder()
                .retryIfExceptionOfType(Exception.class)//遇到Exception类型异常触发重试
                .withWaitStrategy(WaitStrategies.fixedWait(RpcApplication.getRpcConfig().getRetryTime(), TimeUnit.SECONDS))//重试间隔时间
                .withStopStrategy(StopStrategies.stopAfterAttempt(RpcApplication.getRpcConfig().getRetryCount()))//重试最大次数
                .withRetryListener(new RetryListener() {
                    @Override
                    public <V> void onRetry(Attempt<V> attempt) {
                        log.info("第" + attempt.getAttemptNumber() + "次重试");
                    }
                }).build();
        return retryer.call(callable);
    }
}
